package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class EWaiJlActivity extends BaseActivity implements Callback{
	private TextView msg;
	private EditText info,phoneEdit;
	private Button submit;
	private ImageView img,add;
	private String aid,image,summary,phone;
	
	private static final int MSG_AUTH_CANCEL = 2;
	private static final int MSG_AUTH_ERROR= 3;
	private static final int MSG_AUTH_COMPLETE = 4;
	
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ewjl_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		//LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		//rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("获取金币奖励");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setText("  ");
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		aid = getIntent().getExtras().getString("id");
		
		handler = new Handler(this);
		msg = (TextView) findViewById(R.id.ewjl_msg);
		submit = (Button) findViewById(R.id.ewjl_submit);
		info = (EditText) findViewById(R.id.ewjl_text);
		img = (ImageView) findViewById(R.id.ewjl_img);
		add = (ImageView) findViewById(R.id.ewjl_imgadd);
		phoneEdit = (EditText) findViewById(R.id.ewjl_phone);
		
		add.setOnClickListener(this);
		submit.setOnClickListener(this);
		
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==2&&Activity.RESULT_OK==resultCode&&null!=data){
			Uri selectedImage = data.getData();
			String picturePath;
			try {
				String[] filePathColumns={MediaStore.Images.Media.DATA};
				Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null);
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				picturePath= c.getString(columnIndex);
				c.close();
			} catch (Exception e) {
				picturePath = selectedImage.getPath();
			}
			
			Bundle bdl = new Bundle();
			bdl.putString("image", picturePath);
			UIUtil.openActivity(activity, PicCutActivity.class, bdl, 3);

		}
		if(requestCode==3&&Activity.RESULT_OK==resultCode){
			String imgPath = data.getStringExtra("file");
			image = data.getStringExtra("fileremote");
		    ImageLoader.getInstance().displayImage("file:///"+imgPath, img, UIUtil.getImageLoaderDisplayOptions(R.drawable.icon_default_f),new ImageLoadingListener() {
				
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					view.setVisibility(View.GONE);
				}
				
				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					view.setVisibility(View.GONE);
				}
				
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					view.setVisibility(View.VISIBLE);
				}
				
				@Override
				public void onLoadingCancelled(String imageUri, View view) {
					view.setVisibility(View.GONE);
				}
			});
		}  
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.ewjl_imgadd:
			Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库 
		    startActivityForResult(i, 2); 
			break;
		case R.id.ewjl_submit:
			msg.setText("");
			phone = phoneEdit.getText().toString();
			summary = info.getText().toString();
			if((summary==null||summary.trim().length()<=0)&&(image==null||image.trim().length()<=0)&&!StringUtil.isPhone(phone)){
				msg.setText("请填写参加本活动的相关凭证！");
				return;
			}
				final Map<String, String> sbmap = new HashMap<String, String>();
				sbmap.put("auth_token", appContext.getLoginUid());
				sbmap.put("other_info", "");
				sbmap.put("images", image);
				sbmap.put("aid", aid);
				sbmap.put("summary", summary);
				sbmap.put("phone", phone);
				final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
				HttpService.postByText(URLs.USER_ACTIVITY_APPLY, sbmap, new TextHttpResponseHandler() {
							@Override
							public void onSuccess(int arg0, Header[] arg1, String result) {
								mProDialog.dismiss();
								try {
									JSONObject json = new JSONObject(result);
									Log.i("==vcode==", result);
									if (BaseTools.getFrom("status", json).equals("0")) {
										UIUtil.ToastMessage(activity, "提交申请成功");
										finish();
									} else{
										msg.setText(BaseTools.getFrom("message", json));
									}
								} catch (JSONException e) {
									e.printStackTrace();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
								mProDialog.dismiss();
								msg.setText("访问错误");
							}
						});
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		switch(msg.what) {
			case MSG_AUTH_CANCEL: {
				//取消授权
				Toast.makeText(activity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
			} break;
			case MSG_AUTH_ERROR: {
				//授权失败
				Toast.makeText(activity, R.string.auth_error, Toast.LENGTH_SHORT).show();
			} break;
			case MSG_AUTH_COMPLETE: {
				//授权成功
				//Toast.makeText(activity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
				Object[] objs = (Object[]) msg.obj;
				String platform = (String) objs[0];
				
				HashMap<String, String> user = (HashMap<String, String>) objs[1];
				HashMap<String, Object> res = (HashMap<String, Object>) objs[2];
				
				
				final Map<String, String> post = new HashMap<String, String>();
				if(!StringUtil.isEmpty(platform)&&platform.equals(SinaWeibo.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "WEIBO");
					post.put("locate", BaseTools.getFrom("location", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", BaseTools.getFrom("description", res));
				}
				if(!StringUtil.isEmpty(platform)&&platform.equals(QQ.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "QQ");
					post.put("locate", BaseTools.getFrom("province", res)+"-"+BaseTools.getFrom("city", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", "");
				}
				if(!StringUtil.isEmpty(platform)&&platform.equals(Wechat.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "WEIXIN");
					post.put("locate", BaseTools.getFrom("province", res)+"-"+BaseTools.getFrom("city", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", "");
				}
				ClipboardManager c= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
				ClipData clip = ClipData.newPlainText("third", new JSONObject(post).toString());
				c.setPrimaryClip(clip);
				final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
				HttpService.postByText(URLs.USER_THIRD_LOGIN, post, new TextHttpResponseHandler() {
					
					@Override
					public void onSuccess(int arg0, Header[] arg1, String result) {
						mProDialog.dismiss();
						try {
							JSONObject json = new JSONObject(result);
							Log.i("==vcode==", result);
							ClipboardManager c= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
							ClipData clip = ClipData.newPlainText("third", result);
							c.setPrimaryClip(clip);
							if(BaseTools.getFrom("status", json).equals("0")){
								appContext.Login(json.getJSONObject("data").toString());
								afterLogined(activity,new CheckBind() {
									@Override
									public void checkBind(String phone) {
										if(StringUtil.isEmpty(phone)||!StringUtil.isPhone(phone)){
											UIUtil.openActivity(activity, BindPhoneActivity.class, null,204);
										}
									}
								});
								finish();
							}else{
								EWaiJlActivity.this.msg.setText(BaseTools.getFrom("message", json));
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
						mProDialog.dismiss();
						UIUtil.ToastMessage(activity, "登录失败，请稍后重试");
					}
				});
				
			} break;
			
		}
		return false;
	}
	
	public static void login(final String userId, String pass, final Activity activity, final AfterDo after){
		final AppContext appContext = (AppContext) activity.getApplication();
		final Map<String, String> sbmap = new HashMap<String, String>();
		sbmap.put("user", userId);
		sbmap.put("password", pass);
		/*final Handler mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					afterLogined(activity);
					String isfirst = BaseTools.getFrom("isFirstLogin", appContext.getLoginUser(), "false");
					if(isfirst=="true"){
						final CommonDialog show = new CommonDialog(activity, false);
						show.show(true, true, false, "欢迎使用", "欢迎使用赚零花钱，您已经获得50金币奖励，祝您赚零花钱愉快！", "领取", "", new OnClickListener(){
							@Override
							public void onClick(View v) {
								show.dismiss();
								if(after!=null)after.afterDo(activity);
							}
						}, null);
					}else{
						if(after!=null)after.afterDo(activity);
					}
					break;
				default:
					break;
				}
			}
		};*/
		final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
		HttpService.postByText(URLs.USER_LOGIN_SUBMIT, sbmap,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1, String result) {
						mProDialog.dismiss();
						try {
							JSONObject json = new JSONObject(result);
							Log.i("==vcode==", result);
							if (BaseTools.getFrom("status", json).equals("0")) {
								appContext.Login(json.getJSONObject("data").toString());
								afterLogined(activity,null);
								if(after!=null)after.afterDo(activity);
								//mHandler.sendEmptyMessage(1);
							} 
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
						mProDialog.dismiss();
					}
				});
	}
	
	
	
	public static void afterLogined(Context context,CheckBind checkBind){
		WodeFragment.freshPage = true;
//		TanDianFragment.freshPage = true;
//		LingGanFragment.freshPage = true;
//		MainActivity.fragementFreash();
		
		AppContext appContext = (AppContext)context.getApplicationContext();
		userInfo(appContext,checkBind);
		//pushPoint(appContext);
	}
	
	public static void userInfo(final AppContext appContext,final CheckBind checkBind){
		final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				MainActivity.fragementFreash();
			}
		};
		if(appContext.isLogin()){
			final Map<String, String> param = new HashMap<String, String>();
			param.put("auth_token", appContext.getLoginUid());
			HttpService.getByText(URLs.USER_INFO, param, new TextHttpResponseHandler() {
				@Override
				public void onSuccess(int arg0, Header[] arg1, String resultStr) {
					try {
						if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
						JSONObject result = new JSONObject(resultStr);
						if(result.getInt("status")==0){
							JSONObject data = result.getJSONObject("data");
							data.put("auth_token",appContext.getLoginUid());
							appContext.Login(data.toString());
							handler.sendEmptyMessage(1);
							if(checkBind!=null)checkBind.checkBind(BaseTools.getFrom("phone", data));
						}else{
							checkBind.checkBind(BaseTools.getFrom("status", result));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					//UIUtil.ToastMessage(activity, "抱歉，访问失败");
				}
			});
		}else{
			WodeFragment.freshPage = true;
			handler.sendEmptyMessage(1);
		}
	}
	
//	public static void pushPoint(final AppContext appContext){
//		
//		final SharedPreferences sharedPreferences = appContext.getSharedPreferences("POINT_ADD", Context.MODE_PRIVATE);   
//		final int point = sharedPreferences.getInt("point",0);
//		if(point<=0)return;
//		Editor edit = sharedPreferences.edit();
//		edit.putInt("point",0);
//		edit.commit();
//		final MFload jb = new MFload(point);
//		final Map<String, String> sbmap = new HashMap<String, String>();
//		sbmap.put("access-token", appContext.getLoginUid());
//		sbmap.put("coinnum", String.valueOf(point));
//		HttpService.postByText(URLs.USER_POINT_ADD, sbmap, new TextHttpResponseHandler() {
//					@Override
//					public void onSuccess(int arg0, Header[] arg1, String result) {
//						try {
//							JSONObject json = new JSONObject(result);
//							Log.i("==vcode==", result);
//							if (BaseTools.getFrom("status", json).equals("0")) {
//								Log.e("==loggin add 金币==", jb.getF()+"");
//								jb.setF(0);
//								afterLogined(appContext);
//								return;
//							} 
//						} catch (Exception e) { }
//						Editor edit2 = sharedPreferences.edit();
//						edit2.putInt("point",(int)jb.getF()+sharedPreferences.getInt("point",0));
//						edit2.commit();
//					}
//
//					@Override
//					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//						Editor edit2 = sharedPreferences.edit();
//						edit2.putInt("point",(int)jb.getF()+sharedPreferences.getInt("point",0));
//						edit2.commit();
//					}
//				});
//		
//	}
	
	public interface AfterDo{
		public void afterDo(Activity activity);
	}
	
	public interface CheckBind{
		public void checkBind(String phone);
	}
}
